import { useEffect, useState } from "react";

import { ListItemIcon, ListItemText, MenuItem } from "@mui/material";
import { useMatchRoute, useNavigate } from "@tanstack/react-router";
import { useTranslete } from "providers/hooks/useTranslete";

import { NavigateItemProps } from "./index.types";

export const NavigateItem = (props: NavigateItemProps) => {
	const { icon: Icon, path, title, handleClose } = props;

	const [isSelected, setIsSelected] = useState(false);

	const { t } = useTranslete();

	const navigate = useNavigate();
	const matchRoute = useMatchRoute();

	useEffect(() => {
		if (matchRoute({ to: path })) {
			setIsSelected(true);
		} else {
			setIsSelected(false);
		}
	}, [matchRoute]);

	const handleNavigate = (path: string) => {
		navigate({ from: "/", to: path, replace: true });
		handleClose?.();
	};
	return (
		<MenuItem
			sx={{ width: "100%" }}
			selected={isSelected}
			onClick={() => handleNavigate(path)}
		>
			<ListItemIcon>{Icon}</ListItemIcon>
			<ListItemText>{t(title)}</ListItemText>
		</MenuItem>
	);
};
